#include "pkt.h"
#include "cbuf.h"
#include "luas.h"


Pkt s_pkts[MAX_PKT];




int pkt_new(int buffd)
{
    int fd = 0;
    int i;
    for(i = 1; i < MAX_PKT; i++)
    {
        if(s_pkts[i].used == 0)
        {   
            fd = i;
            s_pkts[i].used = 1;
            s_pkts[i].len   = cbuf_read_int(buffd);
            s_pkts[i].msgid = cbuf_read_int(buffd);
            s_pkts[i].buffd = buffd;
            break;
        }
    }
    return fd; 
}
int pkt_free(pktfd)
{
    s_pkts[pktfd].used = 0;
}
const char *pkt_read_utf(int fd)
{
    Pkt *pkt = fd2pkt(fd);
    int buffd = pkt->buffd;
    return cbuf_read_utf(buffd);
}
int pkt_read_int(int fd)
{
    Pkt *pkt = fd2pkt(fd);
    int buffd = pkt->buffd;
    
    return cbuf_read_int(buffd);
}
int pkt_read_short(int fd)
{
    Pkt *pkt = fd2pkt(fd);
    int buffd = pkt->buffd;
    
    return cbuf_read_short(buffd);
}
static int ReadInt(lua_State *L)
{

	int arg_num = LUA_ARGNUM;
	if (arg_num == 1 && LUA_ISNUMBER(1))
	{
        int pktfd = (int)LUA_TONUMBER(1);

        int ir = pkt_read_int(pktfd);
        
        LUA_RETURN(ir);
	}

    LUA_RETURN(0);
}
static int ReadShort(lua_State *L)
{

	int arg_num = LUA_ARGNUM;
	if (arg_num == 1 && LUA_ISNUMBER(1))
	{
        int pktfd = (int)LUA_TONUMBER(1);

        int ir = pkt_read_short(pktfd);
        
        LUA_RETURN(ir);
	}

    LUA_RETURN(0);
}
static int ReadUtf(lua_State *L)
{

	int arg_num = LUA_ARGNUM;
	if (arg_num == 1 && LUA_ISNUMBER(1))
	{
        int pktfd = (int)LUA_TONUMBER(1);

        const char *ir = pkt_read_utf(pktfd);
        
        LUA_RETURNSTR(ir);
	}

    LUA_RETURNSTR("");
}
static luaL_Reg lua_lib[] = 
{
    LUA_FUNC_INIT(ReadInt),
    LUA_FUNC_INIT(ReadShort),
    LUA_FUNC_INIT(ReadUtf),
    {NULL, NULL}
};

int pkt_init()
{
    luas_reg_lib("Pkt", lua_lib);
       
}

